<?php

/**
 * 运营统计： 
 * 给定日期范围， 每日分组-广告/其他渠道分组-渠道-SOURCEID分组
 *
 * @author mengyu wang
 */

require_once 'CommonController.php';

class Admin_DayDataRangeController extends Admin_CommonController
{
    /**
     * 初始化函数
     * 
     * @return void
     */
    public function init()
    {
        parent::init();
        $this->_model = new Application_Model_DayDataRange();
        $this->_ddModel = new Application_Model_DayData();
        $this->_ddpModel = new Application_Model_DayDataPlus();
        $this->_productModel = new Application_Model_PartnerProduct();
        $this->_ddcModel = new Application_Model_DayDataCombine();
        $this->view->title = "管理中心";
    }

 
    /**
     * 日运营报表-日
     */
    public function dayMemberType($startTime)
    {               
        $this->view->title = '运营报表';
        $this->view->reportType = 'op-report';
        $productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
        $this->view->isDay = 1;
        $this->view->startTime = $startTime;
        $this->view->endTime = $startTime;
        $totals = $this->view->totals = $this->_ddModel->getDayMemberType($startTime, $productCode);
        
        if (count($totals)!=0) { 
        for ($i=0; $i<count($totals); ++$i) {           
            foreach ($totals[$i] as $key=>$val) {
                if ($key != 'memberName') {
                    @$totalRow[$key]+=($val);
                } 
            }           
        }
        //客单价统计
        @$totalRow['perPrice'] = $totalRow['okOrderAmount'] / $totalRow['okOrderNum'];
        $this->view->totals[$i] = $totalRow;
        $this->view->totals[$i]['memberName'] = '总计';
        }
    }

    /**
     * 日运营报表-时间段
     */
    public function dateMemberType($startTime, $endTime, $isAll=0)
    {
        $this->view->title = '运营报表';
        $this->view->reportType = 'op-report';
        $productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
        
        if ($startTime) {
           $totals = $this->view->totals = $this->_ddModel->getDateMemberType($startTime, $endTime, $productCode);
        } else {
           $totals = $this->view->totals = $this->_ddModel->getAllMemberType($productCode);
        }
        
        $this->view->isDay = 0; 
        $this->view->startTime = $startTime;
        $this->view->endTime = $endTime;
        
      	if (count($totals)!=0) { 
	        for ($i=0; $i<count($totals); ++$i) {           
	            foreach ($totals[$i] as $key=>$val) {
	                if ($key != 'memberName') {
	                    @$totalRow[$key]+=($val);
	                } 
	            }           
	        }
	        //客单价统计
	        @$totalRow['perPrice'] = $totalRow['okOrderAmount'] / $totalRow['okOrderNum'];
	        $this->view->totals[$i] = $totalRow;
	        $this->view->totals[$i]['memberName'] = '总计';
        }
    }
    
    /**
     * 获取广告渠道列表
     */
    public function expandAdMemberAction()
    {
    	$endTime = $startTime = date('Y-m-d',$this->_request->get('startTime'));
    	$memberName = trim($this->_request->get('memberName'));
    	$osName = trim($this->_request->get('osName'));
    	$productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
    	$members = $this->_model->schedualMember($startTime, $endTime, $productCode,$memberName,$osName);
    	$members = $this->_model->formatNum($members);
    	$json_string = json_encode($members);
    	echo $json_string;
    	exit();
    }
    /**
     * 获得所有渠道列表
    */
    public function expandAllMemberAction()
    {
    	$endTime = $startTime = date('Y-m-d',$this->_request->get('startTime'));
    	$memberName = trim($this->_request->get('memberName'));
    	$osName = trim($this->_request->get('osName'));
    	$productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
    	$members = $this->_model->allMember($startTime, $endTime, $productCode,$memberName,$osName);
    	$members = $this->_model->formatNum($members);
    	$json_string = json_encode($members);
    	echo $json_string;
    	exit();
    }
    
    
    /**
     * 获取广告渠道的SOURCEID列表
     * @return JSON 
     */
    public function adMemberSourceAction()
    {
    	$productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
    	$memberName = $this->_request->get('memberName');
    	$endTime = $startTime = date('Y-m-d',$this->_request->get('startTime'));
    	$osName = trim($this->_request->get('osName'));
        $rows = $this->_model->schedualMemberSourceId($startTime, $endTime, $productCode, $memberName, $osName);
        $rows = $this->_model->formatNum($rows);
        $json_string = json_encode($rows);
        echo $json_string;
        exit();
    }
    /**
     * 获取所有渠道的SOURCEID列表
     * @return JSON 
     */
    public function allMemberSourceAction()
    {
    	$productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
    	$memberName = $this->_request->get('memberName');
    	$endTime = $startTime = date('Y-m-d',$this->_request->get('startTime'));
    	$osName = trim($this->_request->get('osName'));
        $rows = $this->_model->allMemberSourceId($startTime, $endTime, $productCode, $memberName, $osName);
        $rows = $this->_model->formatNum($rows);
        $json_string = json_encode($rows);
        echo $json_string;
        exit();
    }
    /**
     * 获取广告渠道的SUBSOURCEID列表
     * @return JSON 
     */
    public function adMemberSubSourceAction()
    {
    	$productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
    	$memberName = $this->_request->get('memberName');
    	$startTime = $this->_request->get('startTime');
    	$endTime = $this->_request->get('endTime');
    	$sourceId = $this->_request->get('sourceId');
        $rows = $this->_model->schedualMemberSourceIdSourceSubId($startTime, $endTime, $productCode, $memberName, $sourceId);
        $rows = $this->_model->formatNum($rows);
        $json_string = json_encode($rows);
        echo $json_string;
        exit();
    }
    /**
     * 获取其他渠道的列表
     * @return JSON 
     */
    public function expandFreeMemberAction()
    {
    	$productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
    	$endTime = $startTime = date('Y-m-d',$this->_request->get('startTime'));
   		$memberName = $this->_request->get('memberName');
   		$osName = $this->_request->get('osName');
        $rows = $this->_model->noSchedualMember($startTime, $endTime, $productCode, $memberName, $osName);
        $rows = $this->_model->formatNum($rows);
        $json_string = json_encode($rows);
        echo $json_string;
        exit();
    }
    /**
     * 获取其他渠道的SOURCEID列表
     * @return JSON 
     */
    public function freeMemberSourceAction()
    {
    	$productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
    	$memberName = $this->_request->get('memberName');
    	$endTime = $startTime = date('Y-m-d',$this->_request->get('startTime'));
    	$osName = $this->_request->get('osName');
        $rows = $this->_model->noSchedualMemberSourceId($startTime, $endTime, $productCode, $memberName, $osName);
        $rows = $this->_model->formatNum($rows);
        $json_string = json_encode($rows);
        echo $json_string;
        exit();
    }
    
    /**
     * 获取其他渠道的SOURCEID-SUBSOURCEID列表
     * @return JSON 
     */
    public function freeMemberSubSourceAction()
    {
    	$productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
    	$memberName = $this->_request->get('memberName');
    	$startTime = $this->_request->get('startTime');
    	$endTime = $this->_request->get('endTime');
    	$sourceId = $this->_request->get('sourceId');
        $rows = $this->_model->noSchedualMemberSourceIdSourceSubId($startTime, $endTime, $productCode, $memberName, $sourceId);
        $rows = $this->_model->formatNum($rows);
        $json_string = json_encode($rows);
        echo $json_string;
        exit();
    }
    

    
    /**
     * 运营日报总入口
     */
    public function opReportAction()
    {
        $this->view->key = $day = $this->_request->get('day');
        $vars['doType'] = $doType = $this->_request->get('doType') ? $this->_request->get('doType') : 1;
        
        if ($doType == 1 || !$doType) {
        	//按照广告渠道分
	        if ($day == '' || $day == 'today') {
	            //默认为今天
	            $this->opReportToday();
	        } else if ($day == 'yestoday') {
	        	$this->opReportYestoday();
	        } else if ($day == 'last-seven-day') {
	            $this->opReportLastSevenDay();
	        } else if ($day == 'last-thirty-day') {
	            $this->opReportLastThirtyDay();            
	        } else if ($day == 'last-three-month') {
	            $this->opReportLastThreeMonth();
	        } else if($day == 'all') {
	            $this->opReportAll();
	        } else if ($day == 'between') {
	            $this->opReportBetween();
	        }
        } else if ($doType == 2) {
        	//按照所有渠道分
        	if ($day == '' || $day == 'yestoday') {
	            //默认为昨天
	            $this->opReportYestoday(2);
	        } else if ($day == 'last-seven-day') {
	            $this->opReportLastSevenDay(2);
	        } else if ($day == 'last-thirty-day') {
	            $this->opReportLastThirtyDay(2);            
	        } else if ($day == 'last-three-month') {
	            $this->opReportLastThreeMonth(2);
	        } else if($day == 'all') {
	            $this->opReportAll(2);
	        } else if ($day == 'between') {
	            $this->opReportBetween(2);
	        }
        }
		$this->view->vars = $vars;
        $this->renderScript('day-data-range/day-member-type.php');

    }
    /**
     * 运营统计-(时间范围)
     * @param string $startTime
     * @param string $endTime
     * @param int $type
     */
    public function rangeMember($startTime, $endTime, $type = 1)
    {
    	$rows = array();
    	$productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
    	$this->view->memberName = $memberName = $this->_request->get('memberName');
    	$this->view->osName = $osName = $this->_request->get('osName');
    	
    	for ($i = strtotime($endTime); $i >= strtotime($startTime); $i = $i-60*60*24) {   		
    		$rows[] = $this->_model->getDayData($productCode,date('Y-m-d',$i),$memberName,$osName,$type);
    	}
    	$rows[] = $this->_model->getTotalDayData($productCode,$startTime,$endTime,$memberName,$osName,$type);
    	$this->view->rows = $this->_model->formatNum($rows);
    	$this->view->title = '运营报表';
        $this->view->reportType = 'op-report';        
        $this->view->startTime = $startTime;
        $this->view->endTime = $endTime;
        $this->view->members = $this->_model->getMembers($productCode, $startTime, $endTime);
        $this->view->osNames = $this->_model->getOs($productCode, $startTime, $endTime);
    }
    
    /**
     * 运营报表-昨天
     * Enter description here ...
     * @param int type
     */
    public function opReportYestoday($type = 1)
    {
        $this->view->key = 'yestoday';
        $startTime = date('Y-m-d',strtotime("-1 day"));
        $this->rangeMember($startTime,$startTime,$type);    
    }    
     /**
     * 运营报表-今天
     * Enter description here ...
     * @param int type
     */
    public function opReportToday($type = 1)
    {
        $this->view->key = 'today';
        $startTime = date('Y-m-d',strtotime("now"));
        $this->rangeMember($startTime,$startTime,$type);    
    }
    
    /**
     * 运营报表-最近七天
     * Enter description here ...
     * @param int type
     */
    public function opReportLastSevenDay($type = 1)
    {
        $this->view->key = 'last-seven-day';
        $startTime = date('Y-m-d',strtotime("-8 days"));
        $endTime = date('Y-m-d',strtotime("-1 day"));        
        $this->rangeMember($startTime, $endTime, $type);
    }
    
    /**
     * 运营报表-最近30天
     * Enter description here ...
     * @param int type
     */
    public function opReportLastThirtyDay($type = 1)
    {
        $this->view->key = 'last-thirty-day';
        $startTime = date('Y-m-d',strtotime("-31 days"));
        $endTime = date('Y-m-d',strtotime("-1 day"));        
        $this->rangeMember($startTime, $endTime, $type);
    }
    
    /**
     * 运营报表-最近3个月
     * Enter description here ...
     * @param int type
     */
    public function opReportLastThreeMonth($type = 1)
    {
        $this->view->key = 'last-three-month';
        $startTime = date('Y-m-d',strtotime("-3 months"));
        $endTime = date('Y-m-d',strtotime("-1 day"));        
        $this->rangeMember($startTime, $endTime,$type);
    }
    
    /**
     * 运营报表-全部
     * Enter description here ...
     * @param int type
     */
    public function opReportAll($type = 1)
    {
        $this->view->key = 'all';
        $this->view->isDay = 0;
        $this->rangeMember('', '', $type);
    }
    
    /**
     * 运营报表-选择时间段
     * Enter description here ...
     * @param int type
     */
    public function opReportBetween($type = 1)
    {
        $this->view->key = 'between';
        $this->view->title = '运营报表';
        $this->view->reportType = 'op-report';
        if ($this->_request->isPost()) {
            $startTime = $this->_request->get('startTime');
            $endTime = $this->_request->get('endTime');
            $backUrl = $this->view->projectUrl(array('action' => $this->view->reportType,'day'=>'between'));
            if (!$startTime || !$endTime) {
                 echo $this->view->message('请选择时间范围！',$backUrl); exit;
            } else if($startTime>$endTime) {
                 echo $this->view->message('开始时间必须早于结束时间，请重新填写！', $backUrl); exit;  
            } else {
                $this->view->startTime = $startTime;
                $this->view->endTime = $endTime;
            }
            if ($startTime == $endTime) {
            	$this->rangeMember($startTime, $startTime, $type);
            } else {
            	$this->rangeMember($startTime, $endTime, $type);
            }
        }
    }
    /**
     * 展开某一天的广告渠道和其他渠道的总计
     * @return json
     */
    public function expandDayAction()
    {
    	$startTime = date('Y-m-d',$this->_request->get('startTime'));
    	$memberName = trim($this->_request->get('memberName'));
    	$osName = trim($this->_request->get('osName'));
    	$productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
    	$rows = array();
    	$rows = $this->_model->getDayMemberType($startTime, $productCode,$memberName, $osName);
    	$rows[0]['_class'] = 'expandAdMember';
    	$rows[1]['_class'] = 'expandFreeMember';
    	$jsonString = json_encode($this->_model->formatNum($rows));
    	echo $jsonString;
    	exit();
    }
    
    /**
     * 下载日报EXCEL
     */
    public function exportReportAction()
    {
    	//收集广告渠道的数据
        $filter = new Zend_Filter_StripTags();
        $startTime = $filter->filter(trim($this->_request->getPost('startTime')));
        $endTime = $filter->filter(trim($this->_request->getPost('endTime')));              
        $productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
        $product = $this->_productModel->fetchRow("code = '{$productCode}'");

        if ($startTime && $endTime) {
        	if ($startTime != $endTime) {
        		$timeMessage = $startTime . '_' . $endTime;
        	} else {
        		$timeMessage = $startTime;
        	}
        } else {
        	$timeMessage = 'all_';
        }
        
        $memberName = $filter->filter(trim($this->_request->getPost('memberName')));
        $osName = $filter->filter(trim($this->_request->getPost('osName')));
        
         //获取月明细报表
        $monthReportRow = $this->monthReport($productCode, $endTime, $startTime, $memberName, $osName);
        $keyMonthReportRow = array('日期','渠道类型','渠道名称','操作系统', 'ROI','当天总提交订单金额',
            '当天总提交订单量','客单价','广告成本',
            '激活量','当天激活用户订单量',
            '当天激活用户提交订单转化率',  '当天激活用户订单金额',
            '当天ROI',
             '启动次数','启动人数','人均启动'                      
        );
        
        //获取月明细报表-有广告排期的
        $monthAdReportRow = $this->monthAdReport($productCode, $endTime, $startTime, $memberName, $osName);
        //获取月明细报表-无广告排期的
        $monthFreeReportRow = $this->monthFreeReport($productCode, $endTime, $startTime, $memberName, $osName);
        
        //写入到月运营报表EXCEL文件
        $monthReportFile = $this->_ddcModel->writeToExcelMonth('monthReport', $product['name'].' 运营报表 ',$monthReportRow, $monthAdReportRow,$monthFreeReportRow,$productCode,$product['name'],$keyMonthReportRow, null);
              
        //将数据导出到EXCEL文件
        $path = PUBLIC_PATH . "/data/dayData/";
        $filename = $path . $monthReportFile;
        $downloadname = $startTime.'_'.$endTime.'_'.$product['code'].'.xlsx';
        
        header("Content-type:text/html;charset=utf-8");
		header("Content-Disposition: attachment; filename=" . $downloadname);
		readfile($filename);
        
        //文件的删除
        @unlink($filename);
        exit();
    }
    
    /**
     * 获取最近30天的明细报表
     * Enter description here ...
     * @param unknown_type $startTime
     * @param unknown_type $productCode
     */
    public function monthReport($productCode, $startTime, $endTime, $memberName, $osName)
    {
        $start = strtotime($startTime);
        $days = intval(abs((strtotime($startTime) - strtotime($endTime))/24/60/60));
        $totalRow = array();
        $avgRow = array();
        $rows = array();
        for ($i = 0; $i< $days+1; ++$i) {
            $sTime = date('Y-m-d',$start-$i*24*60*60);
            $rows[] = $this->_ddcModel->getDayMemberAdDetail($productCode,$sTime,$memberName, $osName);
        }
        
        //获取总计
        $totalRow = $this->_ddcModel->getMonthTotal($productCode,$startTime,$endTime,$memberName,$osName);
        //获取平均
        $avgRow = $this->_ddcModel->getMonthAvg($productCode,$startTime,$endTime,$memberName, $osName);
        $rows['total'] = $totalRow;
        $rows['avg'] = $avgRow;
        return $rows;
    }
    /**
     * 获取最近30天的明细报表(广告投放)
     * Enter description here ...
     * @param unknown_type $startTime
     * @param unknown_type $productCode
     */
    public function monthAdReport($productCode, $startTime, $endTime, $memberName, $osName)
    {
    	$start = strtotime($startTime);
        $days = intval(abs((strtotime($startTime) - strtotime($endTime))/24/60/60));
        $totalRow = array();
        $avgRow = array();
        $rows = array();
        for ($i = 0; $i< $days+1; ++$i) {
            $sTime = date('Y-m-d',$start-$i*24*60*60);
            $rows[] = $this->_ddcModel->getAdDayMemberAdDetail($productCode,$sTime,$memberName, $osName);
        }
        
        //获取总计
        $totalRow = $this->_ddcModel->getAdMonthTotal($productCode,$startTime,$endTime,$memberName, $osName);
        //获取平均
        $avgRow = $this->_ddcModel->getAdMonthAvg($productCode,$startTime,$endTime,$memberName, $osName);
        $rows['total'] = $totalRow;
        $rows['avg'] = $avgRow;
        return $rows;
    }
    
    /**
     * 获取最近30天的明细报表(免费渠道)
     * Enter description here ...
     * @param unknown_type $startTime
     * @param unknown_type $productCode
     */
    public function monthFreeReport($productCode, $startTime, $endTime, $memberName, $osName)
    {
    	$start = strtotime($startTime);
        $days = intval(abs((strtotime($startTime) - strtotime($endTime))/24/60/60));
        $totalRow = array();
        $avgRow = array();
        $rows = array();
        for ($i = 0; $i< $days+1; ++$i) {
            $sTime = date('Y-m-d',$start-$i*24*60*60);
            $rows[] = $this->_ddcModel->getFreeDayMemberAdDetail($productCode,$sTime,$memberName, $osName);
        }
        
        //获取总计
        $totalRow = $this->_ddcModel->getFreeMonthTotal($productCode,$startTime,$endTime,$memberName, $osName);
        //获取平均
        $avgRow = $this->_ddcModel->getFreeMonthAvg($productCode,$startTime,$endTime,$memberName, $osName);
        $rows['total'] = $totalRow;
        $rows['avg'] = $avgRow;
        return $rows;
    }
}

